package com.example.tally;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import com.example.tally.adapter.AccountAdapter;
import com.example.tally.db.AccountBean;
import com.example.tally.db.DBManager;
import com.example.tally.utils.BudgetDialog;
import com.example.tally.utils.FormatNumberUtil;
import com.example.tally.utils.MoreDialog;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    ListView todayLv;
    // 声明数据源
    ImageView searchIv;
    Button btn_edit;
    ImageButton btn_more;
    List<AccountBean> mDatas;
    AccountAdapter adapter;
    int year, month, day;
    View headerView = null;
    // 头布局相关控件
    TextView topOutTv, topInTv, topbudgetTv, topConTv;
    ImageView topShowIv;
    SharedPreferences preferences;

    int MENU_UPDATE = 0;
    int MENU_DELETE = 1;

    DrawerLayout drawerLayout;
    LinearLayout aboutlayout,settinglayout,historylayout,infolayout,helplayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initTime();
        initView();
        // preferences的初始化,将其设置为私有
        preferences = getSharedPreferences("budget" , Context.MODE_PRIVATE);
        // 添加LIstView的头布局
        addLVHeaderView();
        mDatas = new ArrayList<>();
        // 设置适配器，将每一行数据加载到列表中
        adapter = new AccountAdapter(this, mDatas);
        todayLv.setAdapter(adapter);
    }

    private void initView() {
        todayLv = findViewById(R.id.main_lv);
        btn_edit = findViewById(R.id.main_btn_edit);
        btn_more = findViewById(R.id.main_btn_more);
        searchIv = findViewById(R.id.main_iv_search);
        aboutlayout = findViewById(R.id.dialog_more_btn_about);
        settinglayout = findViewById(R.id.dialog_more_btn_setting);
        historylayout = findViewById(R.id.dialog_more_btn_record);
        infolayout = findViewById(R.id.dialog_more_btn_info);
        helplayout = findViewById(R.id.dialog_more_btn_help);

        aboutlayout.setOnClickListener(this);
        settinglayout.setOnClickListener(this);
        historylayout.setOnClickListener(this);
        infolayout.setOnClickListener(this);
        helplayout.setOnClickListener(this);

        btn_more.setOnClickListener(this);
        btn_edit.setOnClickListener(this);
        searchIv.setOnClickListener(this);
        //setLVLongClickListener();
        registerForContextMenu(todayLv);
        setScrollListener();

        drawerLayout = findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawerLayout, R.string.open, R.string.close);
        drawerLayout.addDrawerListener(toggle);
        toggle.syncState();
    }

    //监听返回按钮，如果抽屉是打开的就关闭，否则返回
    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }

    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, MENU_UPDATE, 0, "修改记录");
        menu.add(0, MENU_DELETE, 0, "删除记录");
    }

    public boolean onContextItemSelected(MenuItem item) {
        //获取上下文菜单适配器
        AdapterView.AdapterContextMenuInfo cmi=(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
        //获取被选择的菜单位置
        int posMenu=cmi.position;
        //将菜单项与列表视图的条目相关联
        AccountBean bean=(AccountBean) adapter.getItem(posMenu-1);
        switch(item.getItemId()){
            case 0://执行该菜单条目的业务逻辑
                ArrayList<String> stringList = new ArrayList<>();
                stringList.add(bean.getId()+"");
                stringList.add(bean.getTypeName()+"");
                stringList.add(bean.getsImageId()+"");
                stringList.add(bean.getBeizhu()==null?"":bean.getBeizhu());
                stringList.add(bean.getMoney()+"");
                stringList.add(bean.getTime()+"");
                stringList.add(bean.getYear()+"");
                stringList.add(bean.getMonth()+"");
                stringList.add(bean.getDay()+"");
                stringList.add(bean.getKind()+"");
                stringList.add("recode");   //代表跳转方向
                Intent intent = new Intent();
                intent.setClass(this, RecordActivity.class);
                intent.putStringArrayListExtra("ListString", stringList);
                this.startActivity(intent);
                break;
            case 1:
                //执行该菜单条目的业务逻辑
                // 弹出提示用户是否删除的对话框
                showDeleteItemDialog(bean);
                break;
        }
        return super.onContextItemSelected(item);
    }

    /**
     * 为ListView添加长按事件
     */
    private void setLVLongClickListener() {
        todayLv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) { // 表示点击了头布局
                    return false;
                }
                // 注意，position是从1开始的，而集合是从0开始的
                int pos = position - 1;
                AccountBean clickBean = mDatas.get(pos); // 获取点击的位置
                // 弹出提示用户是否删除的对话框
                showDeleteItemDialog(clickBean);

                return false;
            }
        });
    }

    private void setScrollListener() {
        //添加滑动事件监听
        todayLv.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // TODO Auto-generated method stub
                switch (scrollState) {
                    case SCROLL_STATE_FLING:
                        // 用户在手指离开屏幕之前，用力滑动一下，屏幕仍在下滑
                        btn_edit.setVisibility(View.INVISIBLE);
//                        btn_more.setVisibility(View.INVISIBLE);
                        break;
                    case SCROLL_STATE_IDLE:
                        //视图已停止滑动"
                        btn_edit.setVisibility(View.VISIBLE);
//                        btn_more.setVisibility(View.VISIBLE);
                        break;
                    case SCROLL_STATE_TOUCH_SCROLL:
                        // "手指没有离开屏幕，视图正在滑动"
                        btn_edit.setVisibility(View.INVISIBLE);
//                        btn_more.setVisibility(View.INVISIBLE);
                    default:
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
    }

    private void showDeleteItemDialog(final AccountBean clickBean) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息").setMessage("您确定要删除该记录吗")
                .setNegativeButton("取消" , null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        int click_id = clickBean.getId();
                        // 执行删除操作
                        DBManager.deleteItemFromAccounttbById(click_id);
                        mDatas.remove(clickBean);    // 实时刷新
                        adapter.notifyDataSetChanged(); // 提示适配器更新数据
                        setTopTvShow(); // 改变头布局TextView显示的内容
                    }
                });
        builder.create().show();
    }

    /**
     * 为ListView添加头布局
     */
    private void addLVHeaderView() {
        // 将布局转换成view 对象
        headerView = getLayoutInflater().inflate(R.layout.item_mainlv_top, null);
        todayLv.addHeaderView(headerView);
        // 初始化控件
        topOutTv = headerView.findViewById(R.id.item_mainlv_top_tv_out);
        topInTv = headerView.findViewById(R.id.item_main_top_tv_in);
        topbudgetTv = headerView.findViewById(R.id.item_mainlv_top_tv_budget);
        topConTv = headerView.findViewById(R.id.item_mainlv_top_tv_day);
        topShowIv = headerView.findViewById(R.id.item_mainlv_top_iv_hide);

        topbudgetTv.setOnClickListener(this);
        headerView.setOnClickListener(this);
        topShowIv.setOnClickListener(this);
    }

    /**
     * 获取今日的具体时间
     */
    private void initTime() {
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH) + 1;
        day = calendar.get(Calendar.DAY_OF_MONTH);
    }

    // 当activity获取焦点的时候会调用此方法
    @Override
    protected void onResume() {
        super.onResume();
        // 加载数据库数据的方法
        loadDBData();
        // 设置顶部布局当中TextView的显示
        setTopTvShow();
    }

    /*设置顶部布局当中TextView的显示*/
    private void setTopTvShow() {
        float incomeOneDay = DBManager.setSumMoneyOneDay(year, month, day, 1);
        float outcomeOneDay = DBManager.setSumMoneyOneDay(year, month, day, 0);
        String infoOneDay = "今日支出: ￥" + FormatNumberUtil.formatFloat(outcomeOneDay) + " 收入: ￥" + FormatNumberUtil.formatFloat(incomeOneDay);
        topConTv.setText(infoOneDay);
        // 获取本月的收入和支出总金额
        float incomeOneMonth = DBManager.getSumMoneyOneMonth(year, month, 1);
        float outcomeOneMonth = DBManager.getSumMoneyOneMonth(year, month, 0);
        topInTv.setText("￥" + FormatNumberUtil.formatFloat(incomeOneMonth));
        topOutTv.setText("￥" + FormatNumberUtil.formatFloat(outcomeOneMonth));
        // 显示预算剩余
        float bmoney = preferences.getFloat("bmoney", 0);
        if(bmoney == 0){
            topbudgetTv.setText("￥ " + 0);
        }else{
            float syMoney = bmoney - outcomeOneMonth;
            topbudgetTv.setText("￥" + FormatNumberUtil.formatFloat(syMoney));
        }

    }

    private void loadDBData() {
        List<AccountBean> list = DBManager.getAccountListOneMonthFromAccounttb(year, month, day);
        mDatas.clear();
        mDatas.addAll(list);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();;
        switch (v.getId()) {
            case R.id.main_iv_search:
                intent = new Intent(this, SearchActivity.class);
                startActivity(intent);
                break;
            case R.id.main_btn_edit:
                intent = new Intent(this, RecordActivity.class);
                startActivity(intent);
                break;
            case R.id.main_btn_more:
                /*MoreDialog moreDialog = new MoreDialog(this);
                moreDialog.show();
                moreDialog.setDialogSize();*/
                //打开滑动菜单  左侧出现
                drawerLayout.openDrawer(GravityCompat.START);
                break;
            case R.id.item_mainlv_top_tv_budget:
                showBudgetDialog();
                break;
            case R.id.item_mainlv_top_iv_hide:
                // 切换TextView明文和密文
                toggleShow();
                break;
            case R.id.dialog_more_btn_about:
                intent.setClass(this, AboutActivity.class);
                this.startActivity(intent);
                break;
            case R.id.dialog_more_btn_setting:
                intent = new Intent(this , SettingActivity.class);
                this.startActivity(intent);
                break;
            case R.id.dialog_more_btn_record:
                intent.setClass(this, HistoryActivity.class);
                this.startActivity(intent);
                break;
            case R.id.dialog_more_btn_info:
                intent = new Intent(this , MonthOrYearCharActivity.class);
                this.startActivity(intent);
                break;
            case R.id.dialog_more_btn_help:
                intent = new Intent(this , HelpActivity.class);
                this.startActivity(intent);
                break;
            case R.id.dialog_more_iv:
                break;
        }
        if (v == headerView) {
            // 头布局被点击了
            intent = new Intent(this, MonthOrYearCharActivity.class);
            startActivity(intent);
        }
    }

    /**
     * 预算显示对话框，因为预算是需要存储的
     */
    private void showBudgetDialog() {
        BudgetDialog dialog = new BudgetDialog(this);
        dialog.show();

        dialog.setOnEnsureListener(new BudgetDialog.OnEnsureListener() {
            @Override
            public void onEnsure(float money) {
                SharedPreferences.Editor edit = preferences.edit();
                edit.putFloat("bmoney" , money);
                edit.commit();

                // 计算剩余金额
                float outcomeOneMonth = DBManager.getSumMoneyOneMonth(year, month, 0);
                float syMoney = money - outcomeOneMonth;
                topbudgetTv.setText("￥ " + syMoney);
            }
        });
    }

    /**
     * 点击头布局的眼睛图标的时候，明文密文切换
     */
    boolean isShow = true;

    private void toggleShow() {
        if (isShow) {
            // 明文——>密文 PasswordTransformationMethod
            PasswordTransformationMethod transformationMethod = PasswordTransformationMethod.getInstance();
            topOutTv.setTransformationMethod(transformationMethod); // 设置隐藏
            topInTv.setTransformationMethod(transformationMethod);
            topbudgetTv.setTransformationMethod(transformationMethod);
            topShowIv.setImageResource(R.mipmap.ih_hide);
            isShow = false;
        } else {
            // 密文——>明文 HideReturnsTransformationMethod
            HideReturnsTransformationMethod returnsTransformationMethod = HideReturnsTransformationMethod.getInstance();
            topOutTv.setTransformationMethod(returnsTransformationMethod); // 设置隐藏
            topInTv.setTransformationMethod(returnsTransformationMethod);
            topbudgetTv.setTransformationMethod(returnsTransformationMethod);
            topShowIv.setImageResource(R.mipmap.ih_show);
            isShow = true;
        }
    }
}